package UILayer;

import java.awt.BorderLayout;

import CtrLayer.CustomerCtr;

import java.util.Set;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableCellRenderer;

import CtrLayer.StockCtr;
import ModelLayer.CustomerCollection;
import javax.swing.SwingConstants;

public class SalesUI extends JInternalFrame
{
	private JTable product_table;
	private JComboBox comboBox;
	private StockCtr stock_ctr;
	private ArrayList<Object[]> selected;
	private JLabel tot_price_filling_lbl;
	private HashMap<String, String> names_and_ids;
	private String[] column_names = { "Art. number", "Name", "Amount",
			"Total cost" };
	private double estimated_cost;


	public SalesUI()
	{
		super("Sale", true, true, true, true);

		setBounds(160, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout(0, 0));
		this.addInternalFrameListener(new InternalFrameAdapter()
		{
			public void internalFrameActivated(InternalFrameEvent e)
			{
				refresh();
			}
		});
		stock_ctr = new StockCtr();
		selected = new ArrayList<>();
		names_and_ids = CustomerCollection.give_names_and_ids();
		JPanel panel_1 = new JPanel();
		getContentPane().add(panel_1, BorderLayout.SOUTH);
		make_ctr_buttons();
		make_table();
	}

	public SalesUI(ArrayList<Object[]> i_selected, String customer)
	{
		super("Sale", true, true, true, true);
		selected = i_selected;
		
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout(0, 0));
		this.addInternalFrameListener(new InternalFrameAdapter()
		{
			public void internalFrameActivated(InternalFrameEvent e)
			{
				refresh();
			}
		});
		stock_ctr = new StockCtr();
		names_and_ids = CustomerCollection.give_names_and_ids();
		JPanel panel_1 = new JPanel();
		getContentPane().add(panel_1, BorderLayout.SOUTH);
		make_ctr_buttons();
		make_table();
		comboBox.addItem(customer);
		//refresh();
	}

	private void make_table()
	{

		final Object[][] filling = null;

		product_table = new JTable();
		product_table.setFillsViewportHeight(true);
		product_table.setModel(new MyTableModel(filling, column_names));

		product_table
				.setPreferredScrollableViewportSize(new Dimension(500, 70));
		product_table.setAutoCreateRowSorter(true);
		product_table.setRowSelectionAllowed(true);
		product_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		product_table.getTableHeader().setReorderingAllowed(false);
		product_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

		product_table.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (e.getClickCount() == 2)
				{
					details();
				}
			}
		});

		JScrollPane scroll_pane = new JScrollPane(product_table);
		scroll_pane.setBorder(new EmptyBorder(5, 10, 5, 10));
		getContentPane().add(scroll_pane, BorderLayout.CENTER);
	}

	private void refresh()
	{
		
		names_and_ids = CustomerCollection.give_names_and_ids();
		Set keys = names_and_ids.keySet();
		String chosen_customer = (String) comboBox.getSelectedItem();
		DefaultComboBoxModel model = (DefaultComboBoxModel) comboBox.getModel();
		model.removeAllElements();
		for(Object key : keys)
		{
			comboBox.addItem(key);
			if(((String) key).equals(chosen_customer))
			{
				comboBox.setSelectedItem(chosen_customer);
			}
			
		}

		estimated_cost = 0;
		for (int i = selected.size()-1; i >= 0; i--)
		{
			if (!(stock_ctr.does_exist((String) selected.get(i)[0])))
			{
				selected.remove(i);
			}
		}
		Object[][] filling = new Object[selected.size()][4];
		int i = 0;
		for (Object[] data : selected)
		{
			
			String name = stock_ctr
					.get_name_via_art_nr(String.valueOf(data[0]));
			double total_cost = stock_ctr.get_sales_line_item_cost(data);
			Object[] temp = { data[0], name, data[1], total_cost };
			filling[i] = temp;
			estimated_cost += total_cost;
			i++;
		}
		product_table.setModel(new MyTableModel(filling, column_names));
		tot_price_filling_lbl.setText(String.valueOf(estimated_cost)+" DKK");
	}

	private void make_ctr_buttons()
	{
		JPanel ctr_btn_panel = new JPanel();
		ctr_btn_panel.setBorder(new EmptyBorder(3, 3, 0, 3));

		getContentPane().add(ctr_btn_panel, BorderLayout.SOUTH);
		GridBagLayout gbl_ctr_btn_panel = new GridBagLayout();
		gbl_ctr_btn_panel.columnWidths = new int[] { 0, 0, 70, 0 };
		gbl_ctr_btn_panel.rowHeights = new int[] { 0, 0 };
		gbl_ctr_btn_panel.columnWeights = new double[] { 1.0, 0.0, 0.0,
				Double.MIN_VALUE };
		gbl_ctr_btn_panel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
		ctr_btn_panel.setLayout(gbl_ctr_btn_panel);

		JButton btn_add = new JButton("Add");
		GridBagConstraints gbc_btn_add = new GridBagConstraints();
		gbc_btn_add.anchor = GridBagConstraints.EAST;
		gbc_btn_add.insets = new Insets(0, 0, 0, 5);
		gbc_btn_add.gridx = 0;
		gbc_btn_add.gridy = 0;
		btn_add.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				add_product();
			}
		});
		ctr_btn_panel.add(btn_add, gbc_btn_add);

		JButton btn_save = new JButton("Save");
		GridBagConstraints gbc_btn_save = new GridBagConstraints();
		gbc_btn_save.anchor = GridBagConstraints.NORTHEAST;
		gbc_btn_save.insets = new Insets(0, 0, 0, 5);
		gbc_btn_save.gridx = 1;
		gbc_btn_save.gridy = 0;
		btn_save.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				save();
			}
		});
		ctr_btn_panel.add(btn_save, gbc_btn_save);

		JButton btn_del = new JButton("Delete");
		GridBagConstraints gbc_btn_del = new GridBagConstraints();
		gbc_btn_del.anchor = GridBagConstraints.WEST;
		gbc_btn_del.gridx = 2;
		gbc_btn_del.gridy = 0;
		btn_del.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				delete();
			}
		});
		ctr_btn_panel.add(btn_del, gbc_btn_del);
		
		JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));

		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.WEST);
		panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel lblNewLabel = new JLabel("Customer");
		panel_1.add(lblNewLabel);

		comboBox = new JComboBox<Object>();
		panel_1.add(comboBox);
		
		JButton search_btn = new JButton("Search");
		search_btn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				CustomerFinder frame = new CustomerFinder();
				getDesktopPane().add(frame);
				frame.setVisible(true);
			}
		});
		panel_1.add(search_btn);

		JPanel panel_2 = new JPanel();
		panel.add(panel_2, BorderLayout.EAST);
		panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel tot_price_lbl = new JLabel("Estimated total price");
		panel_2.add(tot_price_lbl);
		
		tot_price_filling_lbl = new JLabel("New label");
		tot_price_filling_lbl.setFont(new Font("Tahoma", Font.PLAIN, 17));
		panel_2.add(tot_price_filling_lbl);
	}

	private void details()
	{
		int row_index = product_table.getSelectedRow();
		if (row_index != -1)
		{
			if( product_table.getModel().getValueAt(row_index, 0) != null)
			{
				ProductManager p = new ProductManager(
						String.valueOf(product_table.getModel().getValueAt(row_index, 0)), true, false);
				getDesktopPane().add(p);
				Point current_win = getLocationOnScreen();
				int x = (int) current_win.getX() + 20;
				int y = (int) current_win.getY() + 5;
				p.setLocation(x, y);
				p.setVisible(true);
			}
		}
	}

	private void add_product()
	{
		AddProductUI p = new AddProductUI();
		getDesktopPane().add(p);
		Point current_win = getLocationOnScreen();
		int x = (int) current_win.getX() + 20;
		int y = (int) current_win.getY() + 5;
		p.setLocation(x, y);
		p.setVisible(true);
	}

	private void save()
	{
		if (comboBox.getSelectedIndex() != -1)
		{

			if (!(selected.isEmpty()))
			{
				String name = (String) comboBox.getSelectedItem();
				String id = names_and_ids.get(name);
				SaleAdder p = new SaleAdder(selected, id, estimated_cost);
				getDesktopPane().add(p);
				Point current_win = getLocationOnScreen();
				int x = (int) current_win.getX() + 20;
				int y = (int) current_win.getY() + 5;
				p.setLocation(x, y);
				p.setVisible(true);
				dispose();
			}
			else
			{
				JOptionPane.showMessageDialog(this,
						"You need to have added at least one product.", "Error",
						JOptionPane.INFORMATION_MESSAGE);
			}
		}
		else
		{
			JOptionPane.showMessageDialog(this,
					"You need to select a customer.", "Error",
					JOptionPane.INFORMATION_MESSAGE);
		}
	}

	private void delete()
	{
		int row_index = product_table.getSelectedRow();
		if (row_index != -1)
		{
			if( product_table.getModel().getValueAt(row_index, 0) != null)
			{
				for (Object[] data : selected)
				{
					if (data[0].equals(product_table.getModel().getValueAt(
							row_index, 0)))
					{
						selected.remove(data);
						break;
					}
				}
			}
		}
		refresh();
	}

	class AddProductUI extends JInternalFrame
	{
		private JTextField search_tf;
		private JTable product_table;

		private String[] column_names = { "Art. number", "Name", "Quantity",
				"Category", "Amount qualified for discount", "Location",
				"Price" };

		public AddProductUI()
		{
			super("Add product", true, true, true, true);
			setBounds(100, 100, 450, 300);

			make_search();
			make_ctr_btns();
			make_table();

		}

		private void make_ctr_btns()
		{
			JPanel panel = new JPanel();
			getContentPane().add(panel, BorderLayout.SOUTH);
			panel.setLayout(new BorderLayout(0, 0));

			JButton add_btn = new JButton("Add");
			add_btn.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					add();
				}
			});
			panel.add(add_btn, BorderLayout.WEST);

			JButton cancel_btn = new JButton("Cancel");
			cancel_btn.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					dispose();
				}
			});
			panel.add(cancel_btn, BorderLayout.EAST);
		}

		private void make_search()
		{
			JPanel panel_1 = new JPanel();
			getContentPane().add(panel_1, BorderLayout.NORTH);
			panel_1.setLayout(new BorderLayout(0, 0));
			JPanel panel_2 = new JPanel();
			panel_1.add(panel_2, BorderLayout.WEST);
			panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

			JLabel search_lbl = new JLabel("Name/ID");
			panel_2.add(search_lbl);

			search_tf = new JTextField();
			panel_2.add(search_tf);
			search_tf.setColumns(10);

			JButton search_btn = new JButton("Search");
			search_btn.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					search();
				}
			});
			panel_2.add(search_btn);
			JButton clear_btn = new JButton("Clear");
			clear_btn.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					search_tf.setText("");
					refresh_inner();
				}
			});
			panel_2.add(clear_btn);
		}

		private void make_table()
		{
			JScrollPane scrollPane = new JScrollPane();
			getContentPane().add(scrollPane, BorderLayout.CENTER);

			final Object[][] filling = stock_ctr.display_all_products();

			product_table = new JTable();

			product_table.setFillsViewportHeight(true);
			product_table.setModel(new MyTableModel(filling, column_names));

			product_table.setPreferredScrollableViewportSize(new Dimension(500,
					70));
			product_table.setAutoCreateRowSorter(true);
			product_table.setRowSelectionAllowed(true);
			product_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			product_table.getColumnModel().getColumn(4).setMinWidth(160);
			product_table.getTableHeader().setReorderingAllowed(false);
			product_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

			product_table.addMouseListener(new MouseAdapter()
			{
				@Override
				public void mouseClicked(MouseEvent e)
				{
					if (e.getClickCount() == 2)
					{
						add();
					}
				}
			});

			DefaultTableCellRenderer right_renderer = new DefaultTableCellRenderer();
			right_renderer.setHorizontalAlignment(JLabel.RIGHT);
			product_table.setDefaultRenderer(String.class, right_renderer);

			JScrollPane scroll_pane = new JScrollPane(product_table);
			scroll_pane.setBorder(new EmptyBorder(5, 10, 5, 10));
			getContentPane().add(scroll_pane, BorderLayout.CENTER);
		}

		private void add()
		{
			Object[] data = new Object[2];
			boolean ok = true;
			int row_index = product_table.getSelectedRow();
			if (row_index != -1)
			{
				if( product_table.getModel().getValueAt(row_index, 0) != null)
				{
					data[0] = String.valueOf(product_table.getModel().getValueAt(
							row_index, 0));
	
					for (Object[] position : selected)
					{
						if (position[0].equals(data[0]))
						{
							selected.remove(position);
							break;
						}
					}
					if (ok)
					{
						String quantity = JOptionPane
								.showInputDialog("Please input the amount of the product");
						if (is_numeric(quantity))
						{
							if (Integer.parseInt(quantity) > 0)
							{
								if (stock_ctr
										.is_such_amount((String) data[0], quantity))
								{
									data[1] = Integer.parseInt(quantity);
									selected.add(data);
									refresh_inner();
									refresh();
									//dispose();
		
								}
								else
								{
									JOptionPane.showMessageDialog(
													this,
													"Couldn't add a product.\nAmount higher than available quantity.",
													"Error",
													JOptionPane.INFORMATION_MESSAGE);
								}
							}
							else
							{
								JOptionPane.showMessageDialog(
												this,
												"Couldn't add a product.\nAmount must be greater than 0.",
												"Error",
												JOptionPane.INFORMATION_MESSAGE);
							}
						}
						else
						{
							JOptionPane.showMessageDialog(
											this,
											"Couldn't add a product.\nAmount typed incorrectly.",
											"Error",
											JOptionPane.INFORMATION_MESSAGE);
						}

					}
				}
			}
		}

		private void search()
		{
			Object[][] filling = new Object[1][6];
			String contents = search_tf.getText();
			if (is_numeric(contents))
			{
				filling[0] = stock_ctr.find_product_by_art_nr(contents, false,
						false);
			}
			else
			{
				filling[0] = stock_ctr.find_product_by_name(contents, false,
						false);
			}
			product_table.setModel(new MyTableModel(filling, column_names));
		}
		
		private void refresh_inner()
		{
			Object[][] filling = stock_ctr.display_all_products();
			product_table.setModel(new MyTableModel(filling, column_names));
			product_table.getColumnModel().getColumn(4).setMinWidth(180);
		}

		private boolean is_numeric(String checker)
		{
			try
			{
				int i = Integer.parseInt(checker);
			}
			catch (NumberFormatException nfe)
			{
				return false;
			}
			return true;
		}

	}
	
	 class CustomerFinder extends JInternalFrame
	 {
	 	private JTextField text_field;
	 	private CustomerCtr customers;
	 	private JTable table;
	 	private String[] column_names = { "Client Number", "Name", "Phone", "Address","Postal code" };
	 	
	 	public CustomerFinder()
	 	{
	 		super("Find customer", true, true, true, true);
	 		getContentPane().setForeground(new Color(255, 153, 0));
	 		this.addInternalFrameListener(new InternalFrameAdapter()
	 		{
	 			public void internalFrameActivated(InternalFrameEvent e)
	 			{
	 				refill_table();
	 			}
	 		});
	 		customers = new CustomerCtr();
	 		fill_frame();
	 	}

	 	private void refresh_inner()
	 	{
	 		refill_table();

	 	}

	 	private void refill_table()
	 	{
	 		Object[][] filling = customers.display_all_customers();
	 		table.setModel(new MyTableModel(filling, column_names));

	 	}

	 	private void make_table()
	 	{

	 		Object[][] filling = customers.display_all_customers();
	 		JPanel ctr_btn_panel = new JPanel();
	 		ctr_btn_panel.setBackground(new Color(255, 153, 0));
	 		ctr_btn_panel.setBorder(new EmptyBorder(3, 3, 0, 3));
	 		
	 		getContentPane().add(ctr_btn_panel, BorderLayout.SOUTH);
	 		ctr_btn_panel.setLayout(new BorderLayout(0, 0));

	 		JPanel panel = new JPanel();
	 		panel.setBackground(new Color(255, 153, 0));
	 		ctr_btn_panel.add(panel, BorderLayout.EAST);

	 		JButton choose_btn = new JButton("Choose");
	 		panel.add(choose_btn);
	 		choose_btn.addActionListener(new ActionListener()
	 		{
	 			public void actionPerformed(ActionEvent e)
	 			{
	 				choose();
	 			}
	 		});

	 		JButton cancel_btn = new JButton("Cancel");
	 		panel.add(cancel_btn);
	 		cancel_btn.addActionListener(new ActionListener()
	 		{
	 			public void actionPerformed(ActionEvent e)
	 			{
	 				dispose();
	 			}
	 		});

	 		JPanel panel_1 = new JPanel();
	 		panel_1.setBackground(new Color(255, 153, 0));
	 		ctr_btn_panel.add(panel_1, BorderLayout.WEST);

	 		JButton btn_det = new JButton("Details");
	 		panel_1.add(btn_det);
	 		btn_det.addActionListener(new ActionListener()
	 		{
	 			public void actionPerformed(ActionEvent e)
	 			{
	 				view();
	 			}
	 		});

	 		JPanel panel_2 = new JPanel();
	 		getContentPane().add(panel_2, BorderLayout.CENTER);

	 		table = new JTable();
	 		table.setForeground(Color.WHITE);
	 		table.setFont(new Font("Tahoma", Font.PLAIN, 11));
	 		table.setBackground(new Color(127, 127, 127));
	 		table.setFillsViewportHeight(true);
	 		table.setModel(new MyTableModel(filling, column_names));

	 		table.setPreferredScrollableViewportSize(new Dimension(500, 70));
	 		table.setAutoCreateRowSorter(true);
	 		table.setRowSelectionAllowed(true);
	 		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	 		table.getTableHeader().setReorderingAllowed(false);
	 		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
	 		table.addMouseListener(new MouseAdapter()
	 		{
	 			public void mouseClicked(MouseEvent e)
	 			{
	 				if (e.getClickCount() == 2)
	 				{
	 					view();
	 				}
	 			}
	 		});
	 		

	 		DefaultTableCellRenderer right_renderer = new DefaultTableCellRenderer();
	 		right_renderer.setHorizontalAlignment(JLabel.RIGHT);
	 		table.setDefaultRenderer(String.class, right_renderer);

	 		JScrollPane scroll_pane = new JScrollPane(table);
	 		scroll_pane.setBorder(new EmptyBorder(5, 10, 5, 10));
	 		getContentPane().add(scroll_pane, BorderLayout.CENTER);
	 	}

	 	private void make_search(JPanel panel)
	 	{
	 		JPanel search_panel = new JPanel();
	 		search_panel.setBorder(null);
	 		search_panel.setBackground(new Color(255, 153, 0));
	 		panel.add(search_panel, BorderLayout.WEST);
	 		search_panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

	 		JLabel lblNewLabel = new JLabel("Name/ID");
	 		search_panel.add(lblNewLabel);

	 		text_field = new JTextField();
	 		search_panel.add(text_field);
	 		text_field.setColumns(20);

	 		JButton btn_search = new JButton("Search");
	 		btn_search.addActionListener(new ActionListener()
	 		{
	 			public void actionPerformed(ActionEvent e)
	 			{
	 				search();
	 			}
	 		});
	 		search_panel.add(btn_search);

	 		JButton btn_clear = new JButton("Clear");
	 		btn_clear.addMouseListener(new MouseAdapter()
	 		{
	 			public void mouseClicked(MouseEvent e)
	 			{
	 				refresh_inner();
	 				text_field.setText("");
	 			}
	 		});
	 		search_panel.add(btn_clear);

	 	}

	 	private void choose()
	 	{
	 		int row_index = table.getSelectedRow();
	 		if (row_index != -1)
	 		{
	 			if( table.getModel().getValueAt(row_index, 0) != null)
	 			{
	 				comboBox.setSelectedItem((String) table.getModel().getValueAt(row_index, 1));
	 				dispose();
	 			}
	 		}
	 		
	 	}

	 	private void view()
	 	{
	 		int row_index = table.getSelectedRow();
	 		if (row_index != -1)
	 		{
	 			if( table.getModel().getValueAt(row_index, 0) != null)
	 			{
	 				CustomerManager p = new CustomerManager((String) table.getModel().getValueAt(row_index, 0), 1);
	 				getDesktopPane().add(p);
	 				p.setVisible(true);
	 			}
	 		}
	 	}



	 	private void search()
	 	{
	 		Object[][] fill = new Object[1][5];
	 		String info = text_field.getText();
	 		if (is_numeric(info))
	 		{
	 			if (customers.existing_customer(info))
	 			{
	 			fill[0] = customers.find_customer_by_id(info);
	 			}
	 			else 
	 			{
	 				fill[0]=null;
	 			}
	 		}
	 		else
	 		{
	 			if (customers.find_customer_by_name(info)!=null)
	 			{
	 				fill[0] = customers.find_customer_by_name(info);
	 			}
	 			else 
	 			{
	 				fill[0]=null;
	 			}
	 		}
	 		table.setModel(new MyTableModel(fill, column_names));
	 	}

	 	private void fill_frame()
	 	{
	 		setBounds(100, 100, 450, 300);
	 		getContentPane().setLayout(new BorderLayout(0, 0));
	 		JPanel panel = new JPanel();
	 		panel.setBackground(new Color(255, 153, 0));
	 		panel.setBorder(null);
	 		getContentPane().add(panel, BorderLayout.NORTH);
	 		panel.setLayout(new BorderLayout(0, 0));
	 		make_search(panel);
	 		make_table();
	 	}

	 	private boolean is_numeric(String checker)
	 	{
	 		try
	 		{
	 			int i = Integer.parseInt(checker);
	 		}
	 		catch (NumberFormatException nfe)
	 		{
	 			return false;
	 		}
	 		return true;
	 	}
	 }

}
